package com.sphd.education.activitys;

import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.info.ClassifyTwo;
import com.sphd.education.info.MyInfo;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.view.tagview.TagCloudView;

import org.litepal.crud.DataSupport;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
/*
完成个人资料填写
*
* */
public class FinishMySelfActivity extends AppCompatActivity implements View.OnClickListener {
    Intent intent;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.my_image)
    ImageView myImage;
    @Bind(R.id.my_nickname)
    EditText myNickname;
    @Bind(R.id.my_birthday)
    TextView myBirthday;
    @Bind(R.id.my_userphone)
    TextView myUserphone;
    @Bind(R.id.my_signing)
    EditText mySigning;
    @Bind(R.id.man_sex)
    RadioButton manSex;
    @Bind(R.id.woman_sex)
    RadioButton womanSex;
    @Bind(R.id.interest_lesson_tag_cloud_view)
    TagCloudView interestLessonTagCloudView;
    @Bind(R.id.btn_add)
    TextView btnAdd;
    @Bind(R.id.my_layout)
    LinearLayout myLayout;
    private MyInfo myInfo;
    private String sexRadio;
    //定义显示时间控件
    private Calendar calendar; //通过Calendar获取系统时间
    private int year;
    private int month;
    private int day;
    private List<String> interestList;
    private List<Integer> lesson_ID;
    private Button btn_camera;//相机
    private Button btn_photo;//相册
    private static final int REQUE_CODE_CAMERA = 1;
    private static final int REQUE_CODE_PHOTO = 2;
    private static final int REQUE_CODE_CROP = 3;
    private static final int REQUE_CODE_MAP = 4;
    private String imgName;
    private File cameraFile; // 保存拍照后的图片文件
    private Bitmap cropBitmap; // 保存裁剪后的图片
    private PopupWindow popuWindow;//显示获取图片方式的popuwindows
    private View contentView;
    private String dataimg;
    List<ClassifyTwo> classifyTwoListChecked;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finish_my_self);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initView() {
        intent = getIntent();
        myInfo = (MyInfo) intent.getSerializableExtra("myInfo");
        classifyTwoListChecked=new ArrayList<>();
        interestList = new ArrayList<String>();
        lesson_ID = new ArrayList<Integer>();
        toolbar.setTitle("完善资料");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//这是自带的箭头的返回的监听
            }
        });
        ImageLoader.getInstance().displayImage(EducationUrl.HttpTitle + myInfo.getUserimgurl(),
                myImage, EducationUrl.setImg(R.mipmap.touxiangweishangchuan));
        Log.e("IMAGE",EducationUrl.HttpTitle + myInfo.getUserimgurl());
        myNickname.setText(myInfo.getName());
        if (myInfo.getGender().equals("男")) {
            manSex.setChecked(true);
            sexRadio="男";
        } else {
            womanSex.setChecked(true);
            sexRadio="女";
        }
        if (myInfo.getBirthday().equals("")) {
            myBirthday.setText(EducationUrl.getMonthToday(Calendar.getInstance()));
        } else {
            Date dbDate = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
                dbDate = (Date) dateFormat.parse(myInfo.getBirthday());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String strDate=dateFormat.format(dbDate);
            myBirthday.setText(strDate);
        }
        myUserphone.setText(myInfo.getUsername());
        mySigning.setText(myInfo.getDescription());
        if (myInfo.getLikes().trim().length()>0) {
            String[] strlikes = myInfo.getLikes().split(",");
            if (strlikes.length > 0) {
                String lesson = "\t";
                for (int i = 0; i < strlikes.length; i++) {
                    interestList.add(DataSupport.where("classifytwo_id = ?", Integer.valueOf(strlikes[i].trim()) + "").
                            find(ClassifyTwo.class).get(0)
                            .getClassify());
                }
                interestLessonTagCloudView.setTags(interestList);
            }
        }
        contentView = this.getLayoutInflater().inflate(R.layout.layout_takephoto, null);
        btn_camera = (Button) contentView.findViewById(R.id.camara);
        btn_photo = (Button) contentView.findViewById(R.id.photo);
        //初始化Calendar日历对象
        Calendar mycalendar = Calendar.getInstance(Locale.CHINA);
        Date mydate = new Date(); //获取当前日期Date对象
        mycalendar.setTime(mydate);////为Calendar对象设置时间为当前日期
        year = mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年int
        month = mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
        day = mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
    }

    private void initEvent() {
        myImage.setOnClickListener(this);
        manSex.setOnClickListener(this);
        womanSex.setOnClickListener(this);
        myBirthday.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        MyOnClickListener listener = new MyOnClickListener();
        btn_camera.setOnClickListener(listener);
        btn_photo.setOnClickListener(listener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_image:
                showPopuWindow();
                break;
            case R.id.man_sex:
                sexRadio = "男";
                break;
            case R.id.woman_sex:
                sexRadio = "女";
                break;
            case R.id.my_birthday:
                setBirthDay();
                break;
            case R.id.btn_add:
                intent.setClass(getApplicationContext(), AddInterestingActivity.class);
                startActivityForResult(intent,1);
                break;
        }
    }

    /**
     * 显示PopupWindow用于选择图片上传方式
     */
    public void showPopuWindow() {
        if (null == popuWindow) {
            popuWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            popuWindow.setFocusable(true);
            popuWindow.setBackgroundDrawable(new BitmapDrawable());
            popuWindow.setAnimationStyle(R.style.popu_animation);
        }
        popuWindow.showAtLocation(myLayout, Gravity.BOTTOM, 0, 0);
    }

    private void setBirthDay() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int mYear, int monthOfYear,
                                  int dayOfMonth) {
                myBirthday.setText(new StringBuilder().append(mYear).append("-")
                        .append((monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1) : (monthOfYear + 1))
                        .append("-")
                        .append((dayOfMonth < 10) ? "0" + dayOfMonth : dayOfMonth));
            }
        }, year, month, day);
        datePickerDialog.show();
    }
    //activity 的返回结果
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUE_CODE_CAMERA:
                    startPhotoZoom(Uri.fromFile(cameraFile));
                    break;
                case REQUE_CODE_PHOTO:
                    if (null != data) {
                        startPhotoZoom(data.getData());
                        cropBitmap = data.getParcelableExtra("data");
                    }
                    if (cropBitmap != null) {

                        String qimg = System.currentTimeMillis() + ".png";// 糗事图片

                        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
                        cropBitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
                        byte[] bytes = bStream.toByteArray();
                        dataimg = Base64.encodeToString(bytes, Base64.DEFAULT);
                        myImage.setImageBitmap(cropBitmap);
                    }
                    break;
                case REQUE_CODE_CROP:
                    cropBitmap = data.getParcelableExtra("data");
                    if (cropBitmap != null) {
                        String qimg = System.currentTimeMillis() + ".png";// 糗事图片

                        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
                        cropBitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
                        byte[] bytes = bStream.toByteArray();
                        dataimg = Base64.encodeToString(bytes, Base64.DEFAULT);
                        myImage.setImageBitmap(cropBitmap);//设置控件背景
                    }
                    break;

                default:
                    break;
            }

        }
        if (requestCode==1){
            if (resultCode==1){
                interestList.clear();
                classifyTwoListChecked = (List<ClassifyTwo>) data.getSerializableExtra("checxedList");
                for (int i=0;i<classifyTwoListChecked.size();i++){
                    interestList.add(classifyTwoListChecked.get(i).getClassify());
                }
                Log.e("interestList",interestList.size()+"");
                interestLessonTagCloudView.setTags(interestList);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     */
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUE_CODE_CROP);
    }


    //监听方法 主要是popwindows的两个监听
    class MyOnClickListener implements View.OnClickListener {

        Intent intent = null;

        @Override
        public void onClick(View v) {
            int key = v.getId();
            switch (key) {
                case R.id.photo:
                    intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, REQUE_CODE_PHOTO);
                    popuWindow.dismiss();
                    break;
                case R.id.camara:
                    intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File fileDir;
                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        fileDir = new File(
                                Environment.getExternalStorageDirectory()
                                        + "/user_photos");
                        if (!fileDir.exists()) {
                            fileDir.mkdirs();
                        }
                    } else {
                        Toast.makeText(FinishMySelfActivity.this, R.string.sd_noexit, Toast.LENGTH_SHORT)
                                .show();
                        return;
                    }
                    imgName = System.currentTimeMillis() + ".png";
                    cameraFile = new File(fileDir.getAbsoluteFile() + "/" + imgName);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(cameraFile));
                    startActivityForResult(intent, REQUE_CODE_CAMERA);
                    popuWindow.dismiss();
                    break;

                default:
                    break;
            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_myself_finish, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_finish_btn) {
            myNet();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void myNet() {
        StringRequest changeMineMessage = new StringRequest(Request.Method.POST,
                EducationUrl.HttpTitle + EducationUrl.ChangeMineMessage , new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (response.equals("success")) {
                            setResult(1,null);
                            finish();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                EducationUrl.showToast(FinishMySelfActivity.this, error.toString());

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                MyInfo myInfo = DataSupport.findLast(MyInfo.class);
                map.put("id", myInfo.getUserid() + "");
                map.put("realName", myNickname.getText().toString().trim());
                map.put("gender", sexRadio);
                map.put("birth", myBirthday.getText().toString().trim());
                map.put("description", mySigning.getText().toString().trim());
//                Date dbDate = null;
//                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//                try {
//                    dbDate = (Date) dateFormat.parse(myBirthday.getText().toString().trim());
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                map.put("age", getAge(dbDate)+"");
                if (dataimg != null) {
                    map.put("img", dataimg);
                }
                for (int i = 0; i < classifyTwoListChecked.size(); i++) {
                    lesson_ID.add(classifyTwoListChecked.get(i).getClassifytwo_id());
                }
                String likes = lesson_ID.toString();
                EducationUrl.showLog(likes);
                if (classifyTwoListChecked.size()==0){
                    map.put("likes", myInfo.getLikes());
                }else {
                    map.put("likes", likes.substring(1, likes.length() - 1));
                }
                EducationUrl.showLog(likes);
                return map;
            }
        };
        changeMineMessage.setTag("changeminemessage");
        EducationApplication.getRequestQueue().add(changeMineMessage);

    }

}
